package org.leumasjaffe.initiativeTracker.operator;


import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;


import org.eclipse.jdt.annotation.NonNullByDefault;
import org.leumasjaffe.initiativeTracker.entity.Trap;
import org.leumasjaffe.initiativeTracker.entity.trap.RandomTrap;

import tools.Pair;

/**
 * Class to import traps from a trap file
 * @author Sam Jaffe
 *
 */
@NonNullByDefault
public abstract class TrapImporter {	

	/**
	 * Reads in all of the traps in the traps.txt file
	 * @return Returns an array of traps, matched with their turn index
	 */
	@SuppressWarnings("null")
	public static ArrayList<Pair<Double, Trap>> importTraps(String id) {
		ArrayList<Pair<Double, Trap>> traps = new ArrayList<Pair<Double, Trap>>(); //Initialize the Arraylist
		try (FileInputStream fis = new FileInputStream(id + ".traps"); //Get our file input stream
			DataInputStream dis = new DataInputStream(fis);
			BufferedReader br = new BufferedReader(new InputStreamReader(dis))) { //Put the stream in a buffer
			//Initialize the rest of the variables
			String strLine = "";
			Trap temp = null;
			Double d = null;
			while ((strLine = br.readLine()) != null) { 
				//Read a line to a string and continue only if it is non-null
				if (strLine.equals("BEGIN TRAP DATA::"))
					continue; //Continue on this flag
				else if (strLine.startsWith("TRAP TYPE:: ")) 
					temp = new Trap(RandomTrap.decodeTrap(strLine.substring(12))); 
				//Decode the identity of the trap
				else if (strLine.startsWith("TRAP TURN:: "))
					d = Double.valueOf(strLine.substring(12)); //Decode the turn it runs on
				else if (strLine.equals("END OF TRAP")) {
					traps.add(new Pair<Double, Trap>(d, temp)); //Add the pair to the arraylist
				}
				else if (strLine.equals("END OF DATA STREAM"))
					break; //Break at the end flag, ignoring any other data
			}
			//Close the streams from the top down
			fis.close();
			dis.close();
		} catch (IOException e) {}
		return traps; //Return the array
	}

}
